#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <errno.h>


// 非阻塞轮询

int main()
{
    char buffer[1024];
    int ret = fcntl(0, F_GETFL);
    if(ret < 0)
    {
        std::cerr << "fcntl errror" << std::endl;
        exit(-1);
    }
    fcntl(0, F_SETFL, ret | O_NONBLOCK);
    while(true)
    {
        ssize_t cnt = read(0, buffer, sizeof(buffer) - 1);
        if(cnt > 0)
        {
            buffer[cnt] = '\0';
            std::cout << "echo# " << buffer << std::endl;
        }
        else if(cnt == 0)
        {
            std::cout << "no date" << std::endl;
            return 0;
        }
        // 非阻塞等待，若数据没有准备好，返回值会按出错返回
        else
        {
            if(errno == EWOULDBLOCK || errno == EAGAIN)
            {
                std::cout << "数据尚未就绪" << std::endl;
            }
            else if(errno == EINTR)
            {
                std::cout << "IO Interrupted, try again" << std::endl;
            }
            else
            {
                std::cout << "read error" << std::endl;
            }
        }
        sleep(1);
    }

    return 0;
}